package com.ly.redis.jedis;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.*;

import java.util.Random;

/**
 * @Classname TestJedis
 * @Description TODO
 * @Date 2020/10/2 11:49
 * @Author 冷心影翼
 */
public class TestJedis {



	public static void main(String[] args) {
		testTrancation();
	}

	public static void testTrancation() {
		Jedis connetion = getConnetion();
		connetion.del("user:"+01);
		connetion.del("user:"+02);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("name","ly");
		jsonObject.put("age",20);
		jsonObject.put("id",01);
		String info = jsonObject.toJSONString();
		connetion.watch("user:"+01);
		Transaction multi = connetion.multi();
		try{
			multi.set("user:"+01,info);
			multi.set("user:"+02,info);
			int i = 1/0;
			multi.exec();
		}catch(Exception e){
			multi.discard();
		}finally {
			String s = connetion.get("user:" + 01);
			String s1 = connetion.get("user:" + 02);
			System.out.println(s);
			System.out.println(s1);
			connetion.close();
		}
	}

	public static void testString() {
		Jedis jedis = getConnetion();
		int checkCode = new Random().nextInt(8999)+1000;
		if(jedis.ttl("u1")<=240) {
			System.out.println(jedis.get("u1")+" "+jedis.ttl("u1"));
			jedis.setex("u1",300,checkCode+"");
		}else {
			System.out.println(jedis.ttl("u1"));
		}
	}

	public static Jedis getConnetion() {
		JedisShardInfo jedisShardInfo = new JedisShardInfo("119.23.49.175",6379);
		jedisShardInfo.setPassword("252198ly");
		return new Jedis(jedisShardInfo);
	}
}
